<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 用户列表卡片内容区 -->
        <el-card class="box-card">
            <!-- 搜索 添加 -->
            <el-row :gutter="24">
                <el-col :span="10">
                    <el-input placeholder="请输入用户名查找" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button type="success" slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4" style="margin-left: 200px">
                    <el-button plain type="primary" @click="handleDownload" :loading="downloadLoading">导出 Excel <i class="el-icon-download el-icon--right"></i></el-button>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="showAddUserDialog" style="float: right">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区域 -->
            <el-table :data="userlist" border stripe header-row-class-name="table_header" :header-cell-style="table_header">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="avatar_url" label="头像" align="center">
                    <template slot-scope="scope">
                        <img :src="domain + scope.row.avatar_url"  height="50px"/>
                    </template>
                </el-table-column>
				<el-table-column prop="username" label="用户名" align="center"></el-table-column>
                <el-table-column prop="nickname" label="昵称" align="center"></el-table-column>
                <el-table-column prop="role.role_name" label="角色" align="center"></el-table-column>
                <el-table-column label="状态" width="100px;" align="center">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.state" @change="userStateChanged(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="编辑用户"
                        :enterable="false"
                        placement="top"
                        >
                        <el-button
                        type="primary"
                        icon="el-icon-edit"
                        size="mini"
                        circle
                        @click="showEditUserDialog(scope.row)"
                        ></el-button>
                        </el-tooltip>
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除用户"
                        :enterable="false"
                        placement="top"
                        >
                        <el-button
                        type="danger"
                        icon="el-icon-delete"
                        size="mini"
                        circle
                        @click="removeUserById(scope.row.id)"
                        ></el-button>
                        </el-tooltip>
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="角色分配"
                        :enterable="false"
                        placement="top"
                        >
                        <el-button
                            type="warning"
                            icon="el-icon-setting"
                            size="mini"
                            circle
                            @click="showSetRole(scope.row)"
                        ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNum"
                :page-sizes="[2, 5, 10, 15]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                background
                hide-on-single-page
            ></el-pagination>
        </el-card>

<!--        添加或编辑用户-->
        <el-dialog
            :title="Dialog_title"
            :visible.sync="UserDialogVisible"
            width="50%"
            @close="resetForm('UserFormRef')"
            :close-on-click-modal="false"
            >
            <el-form
                :model="UserForm"
                ref="UserFormRef"
                :rules="UserFormRules"
                label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="UserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="UserForm.nickname"></el-input>
                </el-form-item>
                <el-form-item label="角色：">
                    <el-select v-model="UserForm.role_id" filterable placeholder="请选择">
                        <el-option
                                v-for="item in rolesList"
                                :key="item.role_id"
                                :label="item.role_name"
                                :value="item.role_id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="UserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddOrUpdateUser">确 定</el-button>
            </span>
        </el-dialog>

         <!-- 分配角色对话框 -->
        <el-dialog 
            title="分配角色" 
            :visible.sync="setRoleDialogVisible" 
            width="40%" 
            @close="setRoleDialogClosed"
            center
        >
            <div class="allotRole">
                <p>当前用户：{{userInfo.nickname}}</p>
                <p>当前角色：{{userInfo.role.role_name}}</p>
                <p>
                分配角色：
                <el-select
                    v-model="selectRoleId"
                    filterable
                    allow-create
                    default-first-option
                    placeholder="请选择角色标签"
                >
                    <el-option
                    v-for="item in rolesList"
                    :key="item.role_id"
                    :label="item.role_name"
                    :value="item.role_id"
                    ></el-option>
                </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Qs from "qs"


export default {
    data(){
        return {
            queryInfo: {
                query: '',
                // 当前页数
                pageNum: 1,
                // 每页显示多少数据
                pageSize: 10
            },
            userlist: [],
            total: 0,
            UserDialogVisible: false,
            // 用户添加
            UserForm: {},
            Dialog_state: "",
            Dialog_title: '',
            // 用户添加表单验证规则
            UserFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    {
                        min: 2,
                        max: 10,
                        message: '用户名的长度在2～10个字',
                        trigger: 'blur'
                    }
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 18,
                        message: '用户密码的长度在6～18个字',
                        trigger: 'blur'
                    }
                ],
                role_id: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                ],
            },
             // 分配角色对话框
            setRoleDialogVisible: false,
            // 当前需要被分配角色的用户
            userInfo: {
                username: '',
                role: {role_name: ''}
            },
            // 所有角色数据列表
            rolesList: [],
            // 已选中的角色Id值
            selectRoleId: '',
            downloadLoading: false,
            filename: "用户列表"
        }
    },
    created () {
        this.getRoleList();
        this.getUserList()
    },
    methods: {
        string_split(string){
            if (string.constructor === Array) return string;
            return string.split(",")
        },
        table_header(row, column, rowIndex, columnIndex){
                return 'background-color: #409EFF; color:white;font-size: 14px'
        },
        handleSizeChange (newSize) {
            this.queryInfo.pageSize = newSize;
            this.getUserList()
        },
        handleCurrentChange (newSize) {
            this.queryInfo.pageNum = newSize;
            this.getUserList()
        },
        // 监听添加用户对话框关闭事件
        resetForm(formName) {
            this.UserForm = {};
            this.$refs[formName].resetFields()
        },
        handleDownload() {
            this.downloadLoading = true;
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['id', '用户名', '昵称', '头像url', '角色', '状态', '创建时间', '更新时间'];
                const filterVal = ['id', 'username', 'nickname', 'avatar_url', 'role.role_name', 'state', 'created_at', 'updated_at'];
                const list = this.userlist;
                const data = this.formatJson(filterVal, list);
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: this.filename,
                    autoWidth: true,
                    bookType: 'xlsx',
                });
                this.downloadLoading = false
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j.split('.').length === 2){
                    var key = j.split('.')[0];
                    var value = j.split('.')[1];
                    return v[key][value]
                }
                return v[j]
            }))
        },

        showAddUserDialog(){
            this.Dialog_state = "add";
            this.Dialog_title = "添加用户";
            this.UserDialogVisible = true
        },
        showEditUserDialog (user) {
            this.UserForm = JSON.parse(JSON.stringify(user));
            this.Dialog_state = "edit";
            this.Dialog_title = "编辑用户";
            this.UserDialogVisible = true
        },
        // 监听用户状态改变事件
        async userStateChanged(userInfo){
            const {data: res, status: status} = await this.axios.put(`users/changeState`, {"user_id": userInfo.id, "state": userInfo.state})
            if (status !== 200) {
                userInfo.state = !userInfo.state;
                return this.$message.error('更新用户状态失败')
            }
            this.$message.success('更新用户状态成功！')
        },
        // 获取用户列表
        async getUserList () {
            const { data: res, status: status } = await this.axios.get('users/getUserList', {
                params: this.queryInfo
            });
            if (status !== 200) {
                return this.$message.error('获取用户列表失败！')
            }
            this.userlist = res.data.users;
            this.total = res.data.total
        },
        async getRoleList(){
            // 展示对话框之前，获取所有角色列表
            const { data: res, status: status } = await this.axios.get('roles/getRoleList');
            if (status !== 200) {
                return this.$message.error('获取角色列表失败！')
            }
            this.rolesList = res.data
        },
        // 添加用户
        AddOrUpdateUser() {
            var user_form = JSON.parse(JSON.stringify(this.UserForm));
            if (this.Dialog_state === "add") {
                this.$refs.UserFormRef.validate(async valid => {
                    if (!valid) return;
                    const { data: res, status: status } = await this.axios.post('users/addOneUser', user_form);
                    if (status !== 200) {
                        this.$message.error('添加用户失败！')
                    }
                    this.$message.success('添加用户成功！')
                    this.UserDialogVisible = false;
                    this.getUserList()
                })
            }else {
                this.$refs.UserFormRef.validate(async valid => {
                    if (!valid) return;
                    const { data: res, status: status } = await this.axios.put('users/updateUser', user_form);
                    if (status !== 200) {
                        this.$message.error('更新用户信息失败！')
                    }
                    // 隐藏添加用户对话框
                    this.UserDialogVisible = false;
                    this.$message.success('更新用户信息成功！')
                    this.getUserList()
                })
            }
        },
         // 删除用户
        async removeUserById (id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该用户, 是否继续?',
                '提示',
                {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }
            ).catch(err => err);
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res, status: status } = await this.axios.delete('users/deleteUser', {
                params:{"id": id},
            });
            if (status !== 200) return this.$message.error('删除用户失败！')
            this.$message.success('删除用户成功！');
            this.getUserList()
        },
         // 展示分配角色的对话框
        async showSetRole (role) {
            this.userInfo = role;
            this.setRoleDialogVisible = true
        },
        // 分配角色
        async saveRoleInfo () {
            if (!this.selectRoleId) {
                return this.$message.error('请选择要分配的角色')
            }
            const { data: res, status: status } = await this.axios.put("users/updateRole", Qs.stringify({role_id: this.selectRoleId, user_id: this.userInfo.id}))
            if (status !== 200) {
                return this.$message.error('更新用户角色失败！')
            }
            this.$message.success('更新角色成功！')
            this.getUserList();
            this.setRoleDialogVisible = false
        },
        // 分配角色对话框关闭事件
        setRoleDialogClosed () {
            this.selectRoleId = '';
            this.userInfo = {role:{role_name: ''}}
            this.setRoleDialogVisible = false
        }
    }
}
</script>
<style lang="less" scoped>
.allotRole{
   padding-left: 10% !important;
   line-height: 40px;
}
</style>